<?php
/**
 * Created by PhpStorm
 *
 * @author  : yiyu
 * @time    : 2019/11/5 02:13
 * @desc    : 日志封装
 * @fileName: Log4dd.php
 */

namespace app\core\log;

use think\Log;

class Log4dd
{
    /**
     * 记录错误日志
     *
     * @param $message
     * @param array $params
     * @param \Exception|null $ex
     */
    public static function error($message, $params = [], \Exception $ex = null)
    {
        $flag = microtime(true) . rand(1000, 10000);
        $message .= $flag;

        if (!isset($params['date'])) {
            $params['date'] = date('Y-m-d H:i:s');
        }

        Log::error($message);
        self::info($message, $params, $ex);
    }

    /**
     * 记录 info 日志
     *
     * @param $message
     * @param array $params
     * @param \Exception|null $ex
     */
    public static function info($message, $params = [], \Exception $ex = null)
    {
        $data = ['msg' => $message];
        if (!isset($params['date'])) {
            $data['date'] = date('Y-m-d H:i:s');
        }

        if (!empty($params)) {
            $data['params'] = $params;
        }
        if (!empty($ex)) {
            $data['ex'] = [
                'msg' => $ex->getMessage(),
                'code' => $ex->getCode(),
                'file' => $ex->getFile(),
                'line' => $ex->getLine()
            ];
        }

        $log = json_encode($data, JSON_UNESCAPED_UNICODE);
        if (!empty($ex)) {
            $log .= "\ntrace:" . $ex->getTraceAsString();
        }

        Log::info($log);
    }
}